package com.mxx.common.netty.http.resolvers;

import com.mxx.common.netty.http.NettyHttpRequest;
import com.mxx.common.netty.http.NettyMethod;
import com.mxx.common.netty.http.NettyMethodParameter;
import com.mxx.common.utils.ClassUtil;
import io.netty.handler.codec.http.multipart.FileUpload;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/8/14 23:18
 * @Description: 暂无描述
 */
@Component
public class FileUploadListResolvers extends AbstractFileUploadResolvers {

    @Override
    public boolean match(NettyMethod nettyMethod, NettyMethodParameter methodParameter) {
        Parameter parameter = methodParameter.getParameter();
        if (ClassUtil.isSuperInterface(parameter.getType(), Collection.class)) {
            Type type = parameter.getParameterizedType();
            if (!(type instanceof Class)) {
                Type[] types = ((ParameterizedType) type).getActualTypeArguments();
                if (types[0].equals(FileUpload.class)) {
                    return true;
                }
            }
        }
        return false;

    }

    @Override
    public Object resolvers(NettyMethod nettyMethod, NettyHttpRequest request, NettyMethodParameter methodParameter) throws IOException {
        HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(getFactory(), request);
        requestDecoder.setDiscardThreshold(0);
        List<FileUpload> fileUploads = new ArrayList<>();
        while (requestDecoder.hasNext()) {
            InterfaceHttpData data = requestDecoder.next();
            if (data != null && InterfaceHttpData.HttpDataType.FileUpload.equals(data.getHttpDataType())) {
                FileUpload fileUpload = (FileUpload) data;
                fileUploads.add(fileUpload.copy());
            }
        }
        requestDecoder.destroy();
        request.retain();
        return fileUploads;
    }
}
